package cn.faifai.tagapi.service.BackgroundServices;

import cn.faifai.tagapi.config.HardLinksConfig;
import cn.faifai.tagapi.repository.FileUrlRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Service
public class FileHardLinksClearService {
    @Autowired
    private FileUrlRepository fileUrlRepository;

    @Scheduled(cron = "0 0 0 * * ?")
    public void clearFileHardLinks() {
        File[] roots = File.listRoots();
        for (File root : roots) {
            String hardLinksStr = root.getPath() + "\\" + HardLinksConfig.DIRECTORY;
            try {
                Path hardLinks = Paths.get(hardLinksStr);
                Files.walk(hardLinks).forEach(path -> {
                    if (!hardLinks.toAbsolutePath().equals(path.toAbsolutePath())){
                        String fileName = path.getFileName().toString();
                        String fileUrlId = fileName.substring(0, fileName.indexOf("."));
                        if (!fileUrlRepository.existsById(Long.valueOf(fileUrlId))){
                            try {
                                Files.delete(path);
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }

                });
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
